<?php

declare(strict_types=1);

namespace App\Job;

use App\Core\Log;
use App\Model\PointPosition;
use App\Model\PointPositionCategory;
use App\Model\PositionSupervise;
use App\Model\PositionSuperviseSheet;
use App\Repositories\AreaRepository;
use Hyperf\AsyncQueue\Job;

class PaperListStaticExportJob extends Job
{
    public $params;

    protected $maxAttempts = 2;

    public function __construct($params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        Log::get('queue')->info('paperliststaticexportjob开始执行');
        $header_data=[
            '序号',
            '点位类型',
            '点位名称',
            '点位得分',
            '点位满分',
            '后台督查记录ID',
            '不符合标准(处)',
            '待答复',
            '已答复'
        ];
        $file = $this->params['file_url'];
        $district_id = isset($this->params['district_id'])?$this->params['district_id']:'all';
        $category_id = isset($this->params['category_id'])?$this->params['category_id']:'all';
        $start_time = isset($this->params['start_time'])?$this->params['start_time']:'';
        $end_time = isset($this->params['end_time'])?$this->params['end_time']:'';
        $unit_id = isset($this->params['unit_id'])?$this->params['unit_id']:0;
        $folder = BASE_PATH.'/public'.$file;
        $fp = fopen($folder,'w+');
        if (!empty($header_data)) {
            foreach ($header_data as $key => $value) {
                $header_data[$key] = iconv('utf-8', 'GBK', $value);
            }
            fputcsv($fp, $header_data);
        }
        $columns =[
            'position_supervise.*',
            'position_id',
            'category_id',
            'district_id',
            'name'
        ];
        $categories = PointPositionCategory::query()->withTrashed()->get()->keyBy('id');
        $query = PositionSupervise::query()->orderBy('allscore','desc')->orderBy('position_id','asc')
                    ->join('point_position',function($join){
                        $join->on('position_supervise.position_id','=','point_position.id')
                        ->whereNull('point_position.deleted_at');
                    });
        if($district_id!='all'){
            $query->where('point_position.district_id',$district_id);
        }
        if($category_id!='all'){
            $query->where('point_position.category_id',$category_id);
        }

        if($start_time!=''&&$end_time!=''){
            $query->where('position_supervise.created_at','>=',$start_time)
            ->where('position_supervise.created_at','<=',$end_time);
        }
        if($unit_id){
            $query->join('position_units',function($join) use($unit_id){
                $join->on('position_units.position_id','=','point_position.id')
                    ->where('position_units.unit_id',$unit_id)
                    ->whereNull('position_units.deleted_at');
            });
        }
        $query_count = clone $query;
        $all = $query_count->count('position_supervise.id');
        if($all==0){
            cache()->set('export_'.$this->params['hash_id'],100);
            return false;
        }
        $start_count=0;
        $query->select($columns)->chunk(300,function($supervises) use($fp,$all,&$start_count,$categories){
            foreach ($supervises as $key=>$item){
                //$area=AreaRepository::getInstance()->getById($item->district_id);
                //$row[0] = $user->mobile.' ';
                $zero_num = PositionSuperviseSheet::query()->where('supervise_id',$item['id'])->where('score',0)->count('id');
                $wait_reply_num = PositionSuperviseSheet::query()->where('supervise_id',$item['id'])->where('score',0)
                    ->where('sheet_status',PositionSuperviseSheet::SHEET_STATUS_DEFAULT)->count('id');
                $reply_num = PositionSuperviseSheet::query()->where('supervise_id',$item['id'])->where('score',0)
                    ->where('sheet_status',PositionSuperviseSheet::SHEET_STATUS_REPLY)->count('id');
                $row[0] = ($key+1).' ';
                $row[1] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$categories[$item->category_id]->name);
                $row[2] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$item->name);
                $row[3] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$item->allscore.' ');
                $row[4] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$item->full_score.' ');
                $row[5] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$item->id.' ');
                $row[6] = $zero_num.' ';
                $row[7] = $wait_reply_num.' ';
                $row[8] = $reply_num.' ';
                fputcsv($fp,$row);
            }
            $start_count+=300;
            $progress = $start_count>=$all?1:sprintf('%.2f',$start_count/$all);
            cache()->set('export_'.$this->params['hash_id'],$progress*100);

        });
    }
}
